package tasks.io.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tasks.io.core.ChannelContext;
import tasks.io.core.CloseCode;
import tasks.io.core.Io;
import tasks.io.core.thread.ThreadUtils;

public class IOUtils {
    private static final Logger log = LoggerFactory.getLogger(IOUtils.class);

    public static boolean checkBeforeIO(ChannelContext channelContext) {
        if (channelContext.isWaitingClose) {
            return false;
        }
        if (channelContext.asynchronousSocketChannel == null) {
            log.error("{}, 请检查此异常, asynchronousSocketChannel is null, isClosed:{}, isRemoved:{}, {} ", channelContext, channelContext.isClosed, channelContext.isRemoved,
                    ThreadUtils.stackTrace());
            return false;

        } else {
            Boolean open = channelContext.asynchronousSocketChannel.isOpen();
            if (channelContext.isClosed || channelContext.isRemoved) {
                if (open) {
                    try {
                        Io.close(channelContext,
                                "asynchronousSocketChannel is open, but channelContext isClosed: " + channelContext.isClosed + ", isRemoved: " + channelContext.isRemoved, CloseCode.CHANNEL_NOT_OPEN);
                    } catch (Throwable e) {
                        log.error(e.toString(), e);
                    }
                }
                log.info("{}, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, open, channelContext.isClosed, channelContext.isRemoved);
                return false;
            }
            if (!open) {
                log.info("{}, 可能对方关闭了连接, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, open, channelContext.isClosed, channelContext.isRemoved);
                Io.close(channelContext, "asynchronousSocketChannel is not open, 可能对方关闭了连接", CloseCode.CHANNEL_NOT_OPEN);
                return false;
            }
            return true;
        }


    }

}
